<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Fine-SE | 企业工程计划预测及管理系统</title>

    <!-- Bootstrap Core CSS -->
    {% load static %}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>

    <!-- Bootstrap 3.4.1 版本（SB Admin 2兼容版本）-->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">

    <!-- metisMenu 2.7.9 版本 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/metisMenu/2.7.9/metisMenu.min.css" rel="stylesheet">

    <!-- 该文件没有公共CDN，保持原静态文件 -->
    <link href="{% static 'dist/css/sb-admin-2.css' %}" rel="stylesheet">
    <style>
        /* 原完成状态样式修改为仅激活时生效 */
        .step.step-4.active .step-title {
            color: #2ecc71;
            font-weight: bold;
        }

        /* 添加默认状态样式 */
        .step.step-4 .step-title {
            color: #7f8c8d;
        }

        /* 原步骤四圆圈样式调整 */
        .step.step-4.active .step-circle {
            background-color: #2ecc71;
            color: white;
            transform: scale(1.1);
            box-shadow: 0 0 0 2px rgba(46, 204, 113, 0.3);
        }

        .step.step-4 .step-circle {
            background-color: #ecf0f1;
            color: #95a5a6;
        }

        /* 横向步骤链样式 */
        .horizontal-step-chain {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 20px 0 30px;
            padding: 0 15px;
        }

        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            flex: 1;
        }

        .step-circle {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: #ecf0f1;
            color: #95a5a6;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-bottom: 8px;
            z-index: 2;
        }

        .step-title {
            color: #7f8c8d;
            font-size: 14px;
            text-align: center;
        }

        .step-connector {
            position: absolute;
            top: 16px;
            left: 66%;
            width: 100%;
            height: 2px;
            background-color: #ecf0f1;
            z-index: 1;
        }

        .step:last-child .step-connector {
            display: none;
        }

        /* 已完成步骤样式 */
        .step.done .step-circle {
            background-color: #3498db;
            color: white;
        }

        .step.done .step-connector {
            background-color: #3498db;
        }

        .step.done .step-title {
            color: #3498db;
        }

        /* 当前步骤样式 */
        .step.active .step-circle {
            background-color: #2ecc71;
            color: white;
            transform: scale(1.1);
            box-shadow: 0 0 0 2px rgba(46, 204, 113, 0.3);
        }

        .step.active .step-title {
            color: #27ae60;
            font-weight: bold;
        }

        html, body {
            height: 100%;
        }

        #wrapper {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        #page-wrapper {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 15px;
            min-height: 0;
        }

        .iframe-wrapper {
            padding: 0 5px;
            display: flex;
            flex-direction: column;
            height: 100%;
            transition: all 0.5s ease;
        }

        .iframe-container {
            flex: 1;
            min-height: 0;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            background: #f8f9fa;
            overflow: hidden;
            transition: all 0.5s ease;
            display: flex;
            flex-direction: column;
        }

        .iframe-container iframe {
            width: 100%;
            height: 100%;
            border: none;
            flex: 1;
        }

        .row.iframe-row {
            flex: 1;
            min-height: 0;
            margin-left: 0;
            margin-right: 0;
            display: flex;
        }

        .row.dashboard-row {
            flex: 0 0 auto;
        }

        .step-1-2-layout .chat-iframe-wrapper {
            width: 100%;
        }
        .step-1-2-layout .result-iframe-wrapper {
            width: 0;
            padding: 0;
            overflow: hidden;
        }
        .step-3-layout .chat-iframe-wrapper {
            width: 58.3333%;
            display: flex;
        }
        .step-3-layout .result-iframe-wrapper {
            width: 41.6667%;
            display: flex;
            opacity: 1;
            transition: opacity 0.5s ease;
        }

        /* 优化后的3D项目选择器样式 */
        .project-selector-3d {
            position: relative;
            width: 100%;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            perspective: 1000px;
            margin: 10px 0;
            overflow: hidden;
        }

        .project-carousel {
            position: relative;
            width: 50%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
        }

        .nav-arrow {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            padding: 20px 15px;
            color: #555;
            transition: all 0.3s;
            z-index: 10;
            flex-shrink: 0;
        }

        .nav-arrow:hover {
            color: #007bff;
            transform: scale(1.2);
        }

        .nav-arrow:disabled {
            color: #ddd;
            cursor: not-allowed;
            transform: none !important;
        }

        .project-item {
            position: absolute;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
            transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
            opacity: 1;
            width: 100%;
            cursor: pointer;
            white-space: nowrap;
        }

        .project-item.current {
            transform: translateX(0) translateZ(0);
            color: #000;
            font-weight: bold;
            z-index: 3;
        }

        .project-item.prev {
            transform: translateX(-80%) translateZ(-30px);
            color: #aaa;
            font-weight: normal;
            z-index: 2;
            opacity: 0.9;
        }

        .project-item.next {
            transform: translateX(80%) translateZ(-30px);
            color: #aaa;
            font-weight: normal;
            z-index: 2;
            opacity: 0.9;
        }

        .project-item.hidden {
            transform: translateX(0) translateZ(-100px);
            opacity: 0;
            z-index: 1;
        }

        /* 添加项目名称编辑样式 */
        .project-item input.edit-name {
            display: none;
            width: 80%;
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            border: none;
            border-bottom: 2px solid #007bff;
            background: transparent;
            outline: none;
        }

        .project-item.editing .project-name {
            display: none;
        }

        .project-item.editing input.edit-name {
            display: inline-block;
        }

        /* 重命名按钮样式 */
        .rename-btn-container {
            display: flex;
            justify-content: center;
            margin-top: 5px;
        }

        .rename-btn {
            padding: 5px 10px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.3s;
        }

        .rename-btn:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
<div id="wrapper">
    <!-- Navigation -->
    <nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/fine-se">
                <strong>
                    <i style="font-size: 36px; margin-left: 30px;">
                        <font color="black">Fine</font>
                        <font color="black"> - </font>
                        <font color="#00B0F0">SE</font>
                    </i>
                </strong>
            </a>
        </div>

        <ul class="nav navbar-top-links navbar-right">
            <li class="dropdown">
                <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                    <i class="fa fa-tasks fa-fw"></i> <i class="fa fa-caret-down"></i>
                </a>
                <ul class="dropdown-menu dropdown-tasks">
                    <li>
                        <a href="#">
                            <div>
                                <p>
                                    <strong>项目1</strong>
                                    <span class="pull-right text-muted">已完成40%</span>
                                </p>
                                <div class="progress progress-striped active">
                                    <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40"
                                         aria-valuemin="0" aria-valuemax="100" style="width: 40%">
                                        <span class="sr-only">40% Complete (success)</span>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </li>
                    <li class="divider"></li>
                    <li>
                        <a href="#">
                            <div>
                                <p>
                                    <strong>项目2</strong>
                                    <span class="pull-right text-muted">已完成20%</span>
                                </p>
                                <div class="progress progress-striped active">
                                    <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20"
                                         aria-valuemin="0" aria-valuemax="100" style="width: 20%">
                                        <span class="sr-only">20% Complete</span>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </li>
                    <li class="divider"></li>
                    <li>
                        <a href="#">
                            <div>
                                <p>
                                    <strong>项目3</strong>
                                    <span class="pull-right text-muted">已完成60%</span>
                                </p>
                                <div class="progress progress-striped active">
                                    <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60"
                                         aria-valuemin="0" aria-valuemax="100" style="width: 60%">
                                        <span class="sr-only">60% Complete (warning)</span>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </li>
                    <li class="divider"></li>
                    <li>
                        <a href="#">
                            <div>
                                <p>
                                    <strong>项目4</strong>
                                    <span class="pull-right text-muted">已完成80%</span>
                                </p>
                                <div class="progress progress-striped active">
                                    <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80"
                                         aria-valuemin="0" aria-valuemax="100" style="width: 80%">
                                        <span class="sr-only">80% Complete (danger)</span>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </li>
                    <li class="divider"></li>
                    <li>
                        <a class="text-center" href="#">
                            <strong>查看所有项目</strong>
                            <i class="fa fa-angle-right"></i>
                        </a>
                    </li>
                </ul>
            </li>
            <li class="dropdown">
                <a class="dropdown-toggle" data-toggle="dropdown" href="#" style="font-size: 16px; ">
                    <i class="fa fa-user fa-fw"></i> {{ user_full_name }} <i class="fa fa-caret-down"></i>
                </a>
                <ul class="dropdown-menu dropdown-user">
                    <li><a href="#"><i class="fa fa-user fa-fw"></i> 用户信息</a></li>
                    <li><a href="#"><i class="fa fa-gear fa-fw"></i> 设置</a></li>
                    <li class="divider"></li>
                    <li><a href="/logout"><i class="fa fa-sign-out fa-fw"></i> 退出登录</a></li>
                </ul>
            </li>
        </ul>

        <div class="navbar-default sidebar" role="navigation">
            <div class="sidebar-nav navbar-collapse">
                <ul class="nav" id="side-menu">
                    <li class="sidebar-search">
                        <div class="input-group custom-search-form">
                            <input type="text" class="form-control" placeholder="搜索...">
                            <span class="input-group-btn">
                                <button class="btn btn-default" type="button">
                                    <i class="fa fa-search"></i>
                                </button>
                            </span>
                        </div>
                    </li>
                    <li>
                        <a href="/manager"><i class="fa fa-user fa-fw"></i> 个人主页</a>
                    </li>
                    <li class="active">
                        <a href="#" data-toggle="collapse" data-target="#fine-se-menu" aria-expanded="false"
                           class="dropdown-toggle">
                            <i class="fa fa-wrench fa-fw"></i> 使用Fine-SE<i class="fa fa-angle-down pull-right"></i>
                        </a>
                        <ul class="nav nav-second-level collapse in" id="fine-se-menu" aria-expanded="true" style="">
                            <li>
                                <a href="/train">
                                    <i class="fa fa-graduation-cap fa-fw"></i>模型训练
                                </a>
                            </li>
                            <li class="active">
                                <a href="/predict" style="background-color: #e6f2ff;">
                                    <i class="fa fa-calculator fa-fw"></i> 工作量评估
                                </a>
                            </li>
                        </ul>
                    </li>
                    <li>
                        <a href="/assign"><i class="fa fa-tasks fa-fw"></i> 分配任务</a>
                    </li>
                    <li>
                        <a href="/monitorframe"><i class="fa fa-chart-line fa-fw"></i> 监控任务</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div id="page-wrapper">
        <div class="row">
            <div class="col-lg-12 d-flex justify-content-between align-items-center">
                <div class="project-selector-3d">
                    <button class="nav-arrow" id="prevProject"><i class="fa fa-chevron-left"></i></button>

                    <div class="project-carousel" id="projectCarousel">
                        <!-- 项目会通过JavaScript动态添加 -->
                    </div>
                    <button class="nav-arrow" id="nextProject"><i class="fa fa-chevron-right"></i></button>
                </div>
                <h1 class="page-header mb-0">工作量评估</h1>
            </div>
        </div>

        <div class="rename-btn-container">
            <button class="rename-btn" id="renameProject">重命名项目</button>
        </div>

        <div class="row">
            <div class="col-lg-12">
                <div class="horizontal-step-chain">
                    <div class="step active">
                        <div class="step-circle">1</div>
                        <div class="step-title">上传文件</div>
                        <div class="step-connector"></div>
                    </div>
                    <div class="step">
                        <div class="step-circle">2</div>
                        <div class="step-title">选择模型</div>
                        <div class="step-connector"></div>
                    </div>
                    <div class="step">
                        <div class="step-circle">3</div>
                        <div class="step-title">开始预测</div>
                        <div class="step-connector"></div>
                    </div>
                    <div class="step step-4">
                        <div class="step-circle">4</div>
                        <div class="step-title">完成</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row iframe-row" id="iframe-container">
            <div class="iframe-wrapper chat-iframe-wrapper">
                <div class="iframe-container">
                    <iframe src="/predictchat" id="chatIframe"></iframe>
                </div>
            </div>
            <div class="iframe-wrapper result-iframe-wrapper">
                <div class="iframe-container">
                    <iframe src="/result" id="trainresultIframe"></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="/static/vendor/jquery/jquery.min.js"></script>
<script src="/static/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/static/vendor/metisMenu/metisMenu.min.js"></script>
<script src="/static/vendor/raphael/raphael.min.js"></script>
<script src="/static/vendor/morrisjs/morris.min.js"></script>
<script src="/static/data/morris-data.js"></script>
<script src="/static/dist/js/sb-admin-2.js"></script>

<script>
    $(document).ready(function() {
        let currentStep = 1;
        const trainSocket = new WebSocket('ws://' + window.location.host + '/ws/predict/');
        const resultSocket = new WebSocket('ws://' + window.location.host + '/ws/results/?page=predict');

        trainSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            if (data.type === 'training_progress') {
                console.log('训练进度:', data.message);
                saveTrainingProgress(data.progress, data.model_name);
            }
        };

        resultSocket.onmessage = function(e) {
            try {
                const data = JSON.parse(e.data);
                console.log("收到结果数据:", data);

                const resultIframe = document.getElementById('resultIframe');
                if (!resultIframe.contentWindow) {
                    console.error('结果iframe contentWindow未就绪');
                    return;
                }

                if (data.type === 'file_ready') {
                    resultIframe.contentWindow.postMessage({
                        type: 'file_ready',
                        file_name: data.file_name,
                        file_path: data.file_path
                    }, '*');
                    saveTrainingResult(data.file_name, data.file_path);
                } else if (data.type === 'analysis_results') {
                    resultIframe.contentWindow.postMessage({
                        type: 'analysis_results',
                        file_name: data.file_name,
                        results: data.results,
                        total_workload: data.total_workload
                    }, '*');
                    saveAnalysisResults(data.file_name, data.results, data.total_workload);
                } else if (data.type === 'error') {
                    console.error('处理错误:', data.message);
                    alert('处理错误: ' + data.message);
                }
            } catch (error) {
                console.error('处理结果WebSocket消息出错:', error);
            }
        };

        // 保存训练进度
        function saveTrainingProgress(progress, model_name) {
            $.ajax({
                url: '/api/save_training_progress/',
                method: 'POST',
                data: {
                    progress: progress,
                    model_name: model_name,
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                }
            });
        }

        // 保存训练结果
        function saveTrainingResult(file_name, file_path) {
            $.ajax({
                url: '/api/save_training_result/',
                method: 'POST',
                data: {
                    file_name: file_name,
                    file_path: file_path,
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                }
            });
        }

        // 保存分析结果
        function saveAnalysisResults(file_name, results, total_workload) {
            $.ajax({
                url: '/api/save_analysis_results/',
                method: 'POST',
                data: {
                    file_name: file_name,
                    results: JSON.stringify(results),
                    total_workload: total_workload,
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                }
            });
        }

        // 步骤指示器更新逻辑
        function updateStepIndicator(newStep) {
            currentStep = newStep;
            $('.step').removeClass('done active');

            if(newStep === 4) {
                $('.step').addClass('done');
                $('.step.step-4').addClass('active');
            } else {
                for(let i = 1; i < currentStep; i++) {
                    $(`.step:nth-child(${i})`).addClass('done');
                }
                $(`.step:nth-child(${currentStep})`).addClass('active');
            }

            if(newStep !== 4) {
                $('.step.step-4').removeClass('active done');
            }

            updateLayoutForStep(currentStep);

            if (currentStep === 3) {
                startMonitoringResults();
            } else if (currentStep === 4) {
                stopMonitoringResults();
            } else if (currentStep < 3) {
                stopMonitoringResults();
            }

            recordUserAction('step_change', currentStep);
        }

        // 启动结果监控
        function startMonitoringResults() {
            if (resultSocket.readyState === WebSocket.OPEN) {
                resultSocket.send(JSON.stringify({type: 'start_monitoring'}));
                $('#resultIframe').attr('src', '/result');
            } else {
                setTimeout(startMonitoringResults, 500);
            }
        }

        // 停止结果监控
        function stopMonitoringResults() {
            if (resultSocket.readyState === WebSocket.OPEN) {
                resultSocket.send(JSON.stringify({type: 'stop_monitoring'}));
            }
        }

        // 布局更新
        function updateLayoutForStep(step) {
            const $iframeContainer = $('#iframe-container');
            $iframeContainer.removeClass('step-1-2-layout step-3-layout');
            $iframeContainer.addClass(step <= 2 ? 'step-1-2-layout' : 'step-3-layout');
        }

        // 用户行为记录
        function recordUserAction(action, current_step) {
            $.ajax({
                url: '/api/record_user_action/',
                method: 'POST',
                data: {
                    action: action,
                    current_step: current_step,
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                }
            });
        }

        // 初始化步骤指示器
        updateStepIndicator(1);

        const urlParams = new URLSearchParams(window.location.search);
        const selectedProjectId = urlParams.get('project_id');
        const selectedProjectName = urlParams.get('project_name');

        console.log('来自 URL 的项目ID:', selectedProjectId);
        console.log('来自 URL 的项目名称:', selectedProjectName);

        const projects = [
            {% for project in projects %}
                {
                    id: {% if project.id == 'null' %}null{% else %}{{ project.id }}{% endif %},
                    name: "{{ project.name }}",
                    start_date: "{{ project.start_date|date:'Y-m-d' }}"
                }{% if not forloop.last %},{% endif %}
            {% endfor %}
        ];

        function initProjectCarousel() {
            const $carousel = $('#projectCarousel');
            $carousel.empty();

            // 在这里确定 currentProjectIndex
            let selectedId = selectedProjectId === 'null' ? null : parseInt(selectedProjectId);
            currentProjectIndex = 0;

            if (selectedProjectId && selectedProjectName) {
                console.log('尝试匹配项目，ID:', selectedId, '名称:', selectedProjectName);
                currentProjectIndex = projects.findIndex(p => {
                    console.log('比较项目:', p.id, p.name);
                    return p.id === selectedId && p.name.trim() === selectedProjectName.trim();
                });

                if (currentProjectIndex === -1) {
                    console.log('未匹配到项目，回退到默认第一个');
                    currentProjectIndex = 0;
                } else {
                    console.log('成功匹配到索引:', currentProjectIndex);
                }
            }

            // 渲染项目项
            projects.forEach((project, index) => {
                const $item = $('<div>')
                    .addClass('project-item')
                    .attr('data-index', index)
                    .html(`<span class="project-name">${project.name}</span>
                          <input type="text" class="edit-name" value="${project.name}">`);
                $carousel.append($item);
            });

            updateProjectCarousel();
            setupProjectNameEditing();
        }

        // 更新项目选择器显示
        function updateProjectCarousel() {
            const $items = $('.project-item');
            const total = projects.length;
            const $prevBtn = $('#prevProject');
            const $nextBtn = $('#nextProject');

            // 重置按钮状态
            $prevBtn.prop('disabled', false);
            $nextBtn.prop('disabled', false);

            // 处理没有项目的情况
            if (total === 0) {
                $prevBtn.prop('disabled', true);
                $nextBtn.prop('disabled', true);
                return;
            }

            // 处理只有一个项目的情况
            if (total === 1) {
                $items.removeClass('current prev next hidden editing');
                $items.eq(0).addClass('current');
                $prevBtn.prop('disabled', true);
                $nextBtn.prop('disabled', true);
                return;
            }

            const prevIndex = (currentProjectIndex - 1 + total) % total;
            const nextIndex = (currentProjectIndex + 1) % total;

            $items.removeClass('current prev next hidden editing');

            // 设置当前项目
            $items.eq(currentProjectIndex).addClass('current');
            $items.eq(prevIndex).addClass('prev');
            $items.eq(nextIndex).addClass('next');

            // 处理只有两个项目的情况
            if (total === 2) {
                if (currentProjectIndex === 0) {
                    $items.eq(0).addClass('current').removeClass('prev next');
                    $items.eq(1).addClass('next').removeClass('prev current');
                    $prevBtn.prop('disabled', true);
                } else {
                    $items.eq(1).addClass('current').removeClass('prev next');
                    $items.eq(0).addClass('prev').removeClass('next current');
                    $nextBtn.prop('disabled', true);
                }
            }

            // 隐藏其他项目
            $items.each(function(index) {
                if (index !== currentProjectIndex &&
                    index !== prevIndex &&
                    index !== nextIndex) {
                    $(this).addClass('hidden');
                }
            });

            // 更新隐藏表单值
            $('#currentProjectId').val(projects[currentProjectIndex].id);
            $('#currentProjectName').val(projects[currentProjectIndex].name);
        }

        // 设置项目名称编辑功能
        function setupProjectNameEditing() {
            // 双击项目重命名
            $('.project-item').on('dblclick', function() {
                startEditing($(this));
            });

            // 重命名按钮点击事件
            $('#renameProject').click(function() {
                const $currentItem = $('.project-item.current');
                if ($currentItem.length) {
                    startEditing($currentItem);
                }
            });
        }

        // 开始编辑项目名称
        function startEditing($item) {
            if ($item.hasClass('current')) {
                $item.addClass('editing');
                const $input = $item.find('.edit-name');
                $input.focus().select();

                $input.off('blur').on('blur', function() {
                    finishEditing($item);
                });

                $input.off('keypress').on('keypress', function(e) {
                    if (e.which === 13) {
                        finishEditing($item);
                    }
                });
            }
        }

        // 完成项目名称编辑
        function finishEditing($item) {
            const newName = $item.find('.edit-name').val().trim();
            if (newName) {
                const index = $item.data('index');
                projects[index].name = newName;
                $item.find('.project-name').text(newName);
                $item.removeClass('editing');

                if (index === currentProjectIndex) {
                    $('#currentProjectName').val(newName);
                }

                $.ajax({
                    url: '/update_project_name/',
                    method: 'POST',
                    data: {
                        project_id: projects[index].id,
                        new_name: newName,
                        csrfmiddlewaretoken: '{{ csrf_token }}'
                    }
                });
            }
        }

        // 项目导航按钮事件
        $('#prevProject').click(function() {
            if (projects.length <= 1) return;

            currentProjectIndex = (currentProjectIndex - 1 + projects.length) % projects.length;
            updateProjectCarousel();
        });

        $('#nextProject').click(function() {
            if (projects.length <= 1) return;

            currentProjectIndex = (currentProjectIndex + 1) % projects.length;
            updateProjectCarousel();
        });

        // 点击其他地方取消编辑
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.project-item.editing').length &&
                !$(e.target).is('#renameProject')) {
                $('.project-item.editing').each(function() {
                    const $input = $(this).find('.edit-name');
                    $input.val($(this).find('.project-name').text());
                    $(this).removeClass('editing');
                });
            }
        });

        // 消息监听
        window.addEventListener('message', function(event) {
            if (event.data?.type === 'proceed_to_step') {
                console.log("处理proceed_to_step消息", event.data);
                if (event.data.step === 2 && currentStep === 1 && event.data.action === 'file_uploaded') {
                    updateStepIndicator(2);
                    console.log("符合步骤1→2转换条件");
                    const currentProject = projects[currentProjectIndex];
                    const projectId = currentProject.id;
                    const projectName = currentProject.name;

                    console.log('准备发送项目数据到后端 - ID:', projectId, '名称:', projectName);

                    $.ajax({
                        url: '/predictchat/',
                        method: 'POST',
                        data: {
                            project_id: projectId,
                            project_name: projectName,
                            csrfmiddlewaretoken: '{{ csrf_token }}'
                        },
                        success: function(response) {
                            console.log("后端响应成功:", response);
                            const iframe = document.getElementById('chatIframe');
                            if (iframe && iframe.contentWindow) {
                                console.log("iframe已加载")
                                iframe.contentWindow.postMessage({
                                    type: 'ajax_response',
                                    response: response
                                }, '*');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error("AJAX请求失败:", error);
                        }
                    });

                } else if (event.data.step === 3 && currentStep === 2 && event.data.action === 'parameters_submitted') {
                    updateStepIndicator(3);
                    saveModelParameters(event.data.parameters);
                } else if (event.data.step === 1 && event.data.action === 'reupload_file') {
                    updateStepIndicator(1);
                }
            }

            if (event.data?.type === 'training_complete') {
                console.log('训练完成，跳转至步骤4');
                updateStepIndicator(4);
                const currentProject = projects[currentProjectIndex];
                const projectId = currentProject.id;

                fetch('/save_results/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: `project_id=${projectId}`
                })
                .then(response => {
                    if (!response.ok) throw new Error('Network response was not ok');
                    return response.json();
                })
                .then(data => {
                    console.log('Success:', data);
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            }

            if (event.data?.type === 'start_prediction') {
                const username = '{{ user.username }}';
                if (resultSocket.readyState === WebSocket.OPEN) {
                    resultSocket.send(JSON.stringify({
                        type: 'start_prediction',
                        username: username,
                        selected_epochs: event.data.selected_epochs
                    }));
                }
                window.location.href = event.data.path;
            }
        });

        // iframe事件监听
        $('#resultIframe')
            .on('load', () => console.log('结果iframe加载完成'))
            .on('error', () => console.error('结果iframe加载失败'));

        // 页面关闭处理
        window.addEventListener('beforeunload', () => {
            trainSocket.close();
            resultSocket.close();
        });

        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.startsWith(name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // 初始化
        initProjectCarousel();
    });
</script>
</body>
</html>